<template>
  <div class="app-container" v-loading="loading">
    <incrementStudent
      @submit="closeSuccess"
      :classId="model.classId"
      :isEdit="isEdit"
      :item="item"
      v-if="dialogVisible"
      @close="close"
      :dialogVisible="dialogVisible"
    ></incrementStudent>
    <div class="app-top">
      <div style="display: flex; margin-right: 20px">
        <el-input
          v-model="model.searchWords"
          style="width: 50%; margin-right: 20px"
          placeholder="请输入学生姓名或学号"
          size="small"
        />
        <el-select
          @change="selectChange"
          v-model="model.classId"
          placeholder="请选择班级"
          size="small"
        >
          <el-option
            v-for="item in classSource"
            :value="item.pscId"
            :label="item.scName + item.pscName"
            :key="item.pscId"
          ></el-option>
        </el-select>
        <el-button
          style="margin-left: 20px"
          size="small"
          type="primary"
          @click="selectChange"
          >查询</el-button
        >
      </div>
      <input
        @change="uploadTemplate"
        v-if="isShowFile"
        type="file"
        ref="file"
        style="opacity: 0; width: 0; height: 0; overflow: hidden"
      />

      <div>
        <!--        <el-button size="small" type="primary" @click="increment"-->
        <!--          >添加学生</el-button-->
        <!--        >-->
        <!--        <el-button size="small" type="primary" @click="downLoadTemplate"-->
        <!--          >下载模板<i class="el-icon-download el-icon&#45;&#45;right"></i-->
        <!--        ></el-button>-->
        <!--        <el-button-->
        <!--          size="small"-->
        <!--          type="primary"-->
        <!--          @click="uploadFile"-->
        <!--          style="margin-left: 10px"-->
        <!--          >上传<i class="el-icon-upload el-icon&#45;&#45;right"></i-->
        <!--        ></el-button>-->
        <el-button size="small" type="primary" @click="downLoadStudentMessage"
          >导出<i class="el-icon-download el-icon--right"></i
        ></el-button>
      </div>
    </div>
    <el-table
      :row-class-name="xxxTableRowClassName"
      v-loading="isLoading"
      :data="list"
      element-loading-text="Loading"
      :header-cell-style="{
        background: 'rgba(61,157,255,0.05)',
        color: '#333333',
      }"
      fit
      highlight-current-row
      @row-click="setCurrentRow"
    >
      <template slot="empty">
        <span>本班暂无学生</span>
      </template>
      <!--      row-click 行点击事件-->
      <el-table-column
        align="center"
        prop="stuName"
        label="学生姓名"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="stuNum"
        label="学号"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="stuStatusNum"
        label="学籍号"
      ></el-table-column>
      <el-table-column align="center" label="性别" width="110">
        <template slot-scope="scope">
          {{ scope.row.sex == 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="mz"
        class-name="status-col"
        label="民族"
        width="110"
      >
      </el-table-column>
      <el-table-column align="center" label="出生年月" width="130">
        <template slot-scope="scope">
          {{ scope.row.birthTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="免测" width="110">
        <template slot-scope="scope">
          <el-switch
            @change="changeIsExempt(scope.row)"
            v-model="scope.row.isExempt"
            active-value="1"
            :inactive-value="'0'"
            active-color="#13ce66"
          >
          </el-switch>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" prop="phoneNum" label="家长手机号">-->
      <!--        <template slot-scope="scope">-->
      <!--          <p v-for="(item, index) in scope.row.phoneNum" :key="index">-->
      <!--            {{ item | formatPhone }}-->
      <!--          </p>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
        align="center"
        prop="created_at"
        label="操作"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            plain
            type="primary"
            size="small"
            @click="studentEdit($event, scope.row)"
            >编辑</el-button
          >
          <el-button
            plain
            type="danger"
            size="small"
            @click="delSudent($event, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination-page @size="changeSize" @page="changePage" :total="total" />
  </div>
</template>

<script>
import incrementStudent from "@/views/school/student/component/incrementStudent";
import {
  studentList,
  studentImport,
  studentDoFirst,
  exportExcelFun,
  downLoadTempalteApi,
  delStuInfo,
} from "@/api/school/student";
import { classSimList } from "@/api/conmmon";
import Decrypt from "@/utils/Decrypt";
import store from "@/store";
export default {
  data() {
    return {
      list: null,
      isLoading: false,
      loading: false,
      value: false,
      dialogVisible: false,
      item: {},
      isEdit: false,
      model: {
        pageSize: 10,
        pageNum: 1,
        classId: null,
        searchWords: "",
      },
      total: -1,
      studentMessage: {},
      classSource: [],
      isShowFile: false,
    };
  },
  created() {
    this.getClassSource();
  },
  filters: {
    formatPhone(val) {
      let array = Decrypt(val).split("");
      array.splice(3, 4, "****");
      let result = array.join("");
      return result;
    },
  },
  methods: {
    delSudent(evt, row) {
      let target = evt.target;
      this.$confirm("是否确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (target.nodeName == "SPAN") {
            target = evt.target.parentNode;
          }
          target.blur();
          let data = {
            stuId: row.stuId,
          };
          delStuInfo(data).then((res) => {
            if (res.code === 200) {
              this.fetchData();
              this.$message.success("删除成功");
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          if (target.nodeName == "SPAN") {
            target = evt.target.parentNode;
          }
          target.blur();
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    xxxTableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 !== 0) {
        return "statistics-warning-row";
      } else {
        return "";
      }
    },
    downLoadTemplate() {
      downLoadTempalteApi().then((response) => {
        if (response.code === 200) {
          // const url = window.URL.createObjectURL(new Blob([res.data],{ type: 'application/octet-stream;charset=utf-8'}));
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = this.$store.state.user.BASE_URL + response.result;
          link.download = "导入模板.xls";
          document.body.appendChild(link);
          link.click();
          this.$message.success(response.message);
        } else if (response.code === 401) {
          this.$router.replace("/");
          this.$message.error("您的身份信息已过期，请重新登录");
          sessionStorage.removeItem("userInfo");
          sessionStorage.removeItem("token");
          this.$store.commit("user/SET_TOKEN", "");
        } else {
          this.$message.error(response.message);
        }
      });
    },
    selectChange() {
      this.model.pageNum = 1;
      this.fetchData();
    },
    getClassSource() {
      this.loading = true;
      classSimList({
        userId: this.$store.state.user.USER_INFO.id,
        pscShId: this.$store.state.user.USER_INFO.pscShId,
      }).then((response) => {
        this.loading = false;
        if (response.code === 200) {
          if (response.result.length) {
            this.classSource = response.result;
            this.model.classId = response.result[0].pscId;
            this.fetchData();
          } else {
            this.$message.error("您目前没有班级,请联系管理员添加");
          }
        }
      });
    },
    downLoadStudentMessage() {
      exportExcelFun(
        {
          userId: this.$store.state.user.USER_INFO.id,
          classId: this.model.classId,
          schoolId: this.$store.state.user.USER_INFO.pscShId,
        },
        this.$store.state.user.TOKEN
      );
    },

    changeSize(size) {
      this.model.pageSize = size;
      this.fetchData();
    },
    closeSuccess() {
      this.model.pageNum = 1;
      this.model.pageSize = 10;
      this.dialogVisible = false;
      this.fetchData();
    },
    changePage(page) {
      this.model.pageNum = page;
      this.fetchData();
    },
    studentEdit(evt, row) {
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
      this.item = { ...row };
      this.isEdit = true;
      this.dialogVisible = true;
    },
    setCurrentRow(row) {
      this.studentMessage = row;
    },
    changeIsExempt(row) {
      this.isLoading = true;
      studentDoFirst({
        stuId: row.stuId,
        type: "0",
        status: row.isExempt,
      }).then((response) => {
        if (response.code === 200) {
          this.isLoading = false;
        }
      });
    },
    uploadFile(e) {
      this.isShowFile = true;
      this.$nextTick(() => {
        this.$refs.file.click();
      });
    },
    uploadTemplate() {
      let upload_file = this.$refs.file.files[0];
      const upload_file_name = upload_file.name.substring(
        upload_file.name.lastIndexOf(".") + 1
      );
      if (upload_file_name != "xls") {
        this.$message.error("只可以上传xls文件");
        return;
      }
      let formData = new FormData();
      formData.append("file", upload_file);
      formData.append("classId", this.model.classId);
      studentImport({ param: encryption(JSON.stringify(formData)) }).then(
        (response) => {
          if (response.code === 200) {
            this.fetchData();
          } else if (response.code === 401) {
            this.$router.replace("/");
            this.$message.error("您的身份信息已过期，请重新登录");
            sessionStorage.removeItem("userInfo");
            sessionStorage.removeItem("token");
            this.$store.commit("user/SET_TOKEN", "");
          } else {
            this.$message.error(response.message);
          }
        }
      );
      this.isShowFile = false;
    },
    increment() {
      this.dialogVisible = true;
    },
    close() {
      this.dialogVisible = false;
      this.item = {};
      this.isEdit = false;
    },
    async fetchData() {
      this.isLoading = true;
      const result = await studentList({
        ...this.model,
        userId: this.$store.state.user.USER_INFO.id,
        schoolId: this.$store.state.user.USER_INFO.pscShId,
      });
      if (result.code === 200) {
        this.list = result.result;
        this.total = result.total;
      }
      this.isLoading = false;
    },
  },
  components: {
    incrementStudent,
  },
};
</script>
<style scoped lang="scss">
.app-top {
  display: flex;
  justify-content: space-between;

  margin-bottom: 30px;
}
::v-deep .el-table__body-wrapper .statistics-warning-row {
  background: rgba(61, 157, 255, 0.05);
}
</style>
